<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>我的借阅</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <jsp:include page="/inc/head.jsp" flush="true"/>
    <jsp:include page="/inc/footer.jsp" flush="true"/>
    <!-- picker -->
    <script src="${basePath}/js/My97DatePicker/WdatePicker.js"></script>
    <script src="${basePath }/js/tip.js"></script>
    <style>
      .content #rowTable .box {
           border-top:0;
       }
      .content #rowTable .box .bootstrap-table .fixed-table-toolbar {
          position: absolute;
          right: 0;
          top: -44px;
      }
      .content #rowTable .box .bootstrap-table .fixed-table-container {
          margin-top: 10px;
      }
      .content #rowTable .box .bootstrap-table .fixed-table-toolbar  .icon-refresh {
          padding: 3px 0;
      }
    </style>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<!-- Main content -->
<section class="content">
    <!-- /rowToolBar -->
    <div id="listBar" class="btn-group">
        <button id="btn_myReturn" type="button" class="btn btn-default" onclick="returnFileAction()">
            <span class="glyphicon glyphicon-log-out" aria-hidden="true"></span>归还
        </button>
    </div>

    <div id = "rowTable" class="row">
        <div class="col-xs-12">
            <div class="box">
                <div class="box-body table-responsive no-padding">
                    <table id="myTable">
                    </table>
                </div>
            </div>
        </div>
    </div>

    <%--续借申请模态框--%>
    <div id="renewModal" class="modal fade bs-example-modal-lg addUpdateInfo" role="dialog"
         aria-labelledby="myLargeModalLabel">
        <div class="modal-dialog " role="document">
            <div class="modal-content" style="width: 330px;">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="exampleDefineLabel">续借申请</h4>
                </div>
                <div class="modal-body" style="height: 300px;">
                    <form class="form-horizontal form-bordered form-row-strippe" id="renewInfoForm" data-toggle="validator" enctype="multipart/form-data">
                        <table style="width: 100%" id="renewInfoTable">
                            <tr>
                                <td class="content">
                                    续&nbsp;借&nbsp;时&nbsp;间 :
                                </td>
                                <td class="form-group firstTD">
                                    <input type='text' id="renewTime" name="renewTime" onClick='WdatePicker()'/>
                                </td>
                            </tr>
                            <tr>
                                <td class="content">
                                    续&nbsp;借&nbsp;次&nbsp;数 :
                                </td>
                                <td class="form-group firstTD">
                                    <input type='text' id="renewTimes" name="renewTimes" value="" readonly/>
                                </td>
                            </tr>
                            <tr>
                                <td class="content">
                                    续&nbsp;借&nbsp;原&nbsp;因 :
                                </td>
                            </tr>
                            <tr>
                                <td  class="content" colspan="2">
                                    <textarea  type='text' maxlength="50" id="renewPurpose" name="renewPurpose"  value=''  style="width: 97%">
                                    </textarea>
                                </td>
                            </tr>
                            <tr  id="sendPointUserDiv" style="display: none">
                                <td class="content">
                                    指定下级领导审批:
                                </td>
                                <td class="form-group">
                                    <select id="userTable" data-delegateUser="" style="width: 80%">
                                    </select>
                                </td>
                            </tr>
                        </table>
                        <input type="hidden" id="borRegistId" value="" />
                    </form>
                </div>
                <div class="modal-footer bg-info">
                    <button type="button" class="btn green" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="createDefine" onclick="renewSubmit(this);">确认</button>
                </div>
            </div>
        </div>
    </div>
    <%--查看pdf模态框--%>
    <div id="watchPdfModal" class="modal fade bs-example-modal-lg" role="dialog"
         aria-labelledby="myLargeModalLabel" >
        <div class="modal-dialog " role="document">
            <div class="modal-content" style="width:1000px;height: 700px;">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="watchPdf" style="display: inline-block">查看内容</h4>
                    <shiro:hasPermission name="cms:myBorrow:print">
                        <button id="btn_print" type="button" class="btn btn-default" style="margin-left: 50px" onclick="printAction()">
                            <span class="glyphicon glyphicon-print" aria-hidden="true"></span>打印
                        </button>
                    </shiro:hasPermission>
                </div>
                <iframe id="pdfDIV" name="pdfName" style="height: 100%;width: 100%">
                </iframe>
            </div>
        </div>
    </div>
</section>
</body>
<script type="text/javascript">

    var fileTypeJson = {};

    /**************************************** 我的借阅列表数据展示 开始 ***************************************************/
    var $myTable = $("#myTable");
    $(document).ready(function(){

        findAllJudType();

        $myTable.bootstrapTable({
            url: "${basePath}/pcwindow/getBorrowMy",
            striped: true,
//            search: true,
            showRefresh: true,
            showColumns: true,
            minimumCountColumns: 2,
            clickToSelect: true,
            cardView: false,
            detailView: true,
            pagination: true,
            pageSize: 50,
            pageList:[50,100],
            paginationLoop: false,
            sidePagination: 'server',
            silentSort: false,
            smartDisplay: false,
            escape: true,
            searchOnEnterKey: true,
            idField: 'REGISTID',
            maintainSelected: true,
            toolbar: '#toolbar',
            columns:[
                {field: 'ck', checkbox: true},
                {field: 'REGISTID', visible:false},
                {field: 'REGISTERNUM', title: '登记号', align: 'center'},
                {field: 'TITLE', title: '借阅文件', align: 'center'},
                {field: 'FILETYPE', title: '档案类型', align: 'center',formatter:"fileTypeFormat"},
                {field: 'BORTYPE', title: '借阅形式', align: 'center',formatter:'borTypeFormat'},
                {field: 'PLANRETURNTIME', title: '截止时间', align: 'center',formatter:'planReturnTimeFormat'},
                {field: 'overdue', title: '逾期情况', align: 'center',formatter:'overdueFormat'},
                {field: 'action', title: '操作', align: 'center',formatter:'actionFormat'}
            ],
            //注册加载子表的事件。注意下这里的三个参数！
            onExpandRow: function (index, row, $detail) {
                showItemTable(index, row, $detail);
            },
            onLoadSuccess:function(data){
                //无数据隐藏分页
                if(data && data.total == 0){
                    $('.fixed-table-pagination').hide()
                }
            }
        })

        $myTable.bootstrapTable('resetView',{height:setHeight()});

        //禁止鼠标右键
        document.oncontextmenu = function(ev){
            window.event.returnValue=false;
        }

        //禁止鼠标ctrl键  防止ctrl+p
        document.onkeydown = function(){
            if( event.ctrlKey ){
                return false;
            }
        };


    });

    function findAllJudType(){
        $.ajax({
            type: "POST",
            url:"${pageContext.request.contextPath }/pcwindow/findAllJudType",
            dataType:"json",
            async:false,
            success: function(data){
                if (data.length != 0) {
                    var arcTypes = data.rows;
                    for(var i = 0;i < arcTypes.length ;i++){
                        var tyname=arcTypes[i].sortName;
                        var tyid=arcTypes[i].sortNum;
                        fileTypeJson[tyid] = tyname;
                    }
                }
            }
        });
    }

    //展示件的table表单（卷同样展示件内容）
    function showItemTable(index, row, $detail) {
        var fileShape = row.FILESHAPE;
        var parentid = row.FILEID;
        var borType = row.BORTYPE;
        $("body").attr("attr-id",borType);
        $("body").attr("attr-fileShape",fileShape);
        var $child_table = $detail.html('<table id="child_table"></table>').find('table');
        $child_table.bootstrapTable({
            url: '${basePath}/pcwindow/getItemForMyBorrow',
            method: 'get',
            queryParams: { parentid: parentid ,fileShape:fileShape},
            //ajaxOptions: { strParentID: parentid },
            clickToSelect: false,
            detailView: false,//父子表
            uniqueId: "itemId",
            dataType:'json',
            pagination: false,
            /* sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
             pageNumber:1,                       //初始化加载第一页，默认第一页
             pageSize: 10,                       //每页的记录行数（*）
             pageList: [10, 25, 50, 100],*/        //可供选择的每页的行数（*）
            cardView: false,                    //是否显示详细视图
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            showColumns: false,                  //是否显示所有的列
            columns: [
                /* {field: 'ck',checkbox: true},*/
                {field: 'itemNum', title: '序号', align: 'center'},
                {field: 'itemName',title: '文号'},
                {field: 'itemTemporary',title: '单元号', align: 'center', visible:false},
                {field: 'itemSecret',title: '卷内件密级', align: 'center', visible:false},
                {field: 'itemTitle',title: '卷内件题名', align: 'center'},
                {field: 'itemRespons',title: '责任者', align: 'center'},
                {field: 'itemCreateTime',title: '发文日期', align: 'center'},
                {field: 'itemPage',title: '页次', align: 'center', visible:false},
                {field: 'itemCreateDate',title: '创建时间', align: 'center',formatter:'createItemAction', visible:false},
                {field: 'action', title: '操作', align: 'center', formatter: 'actionFormatter', events: 'actionEvents', clickToSelect: false}
            ]
        });
    }

    //初始化文件类型
    function fileTypeFormat(value,row,index){
        return fileTypeJson[value];
    }
    //初始化文件类型
    function borTypeFormat(value,row,index){
        if(value==0){
            return "线上";
        }else{
            return "线下";
        }
    }

    //初始化归还时间格式
    function planReturnTimeFormat(value,row,index){
        return  ChineseTimeYMD(value);
    }

    //初始化逾期归还格式
    function overdueFormat(value,row,index){
        var nowDateLong = new Date().getTime();
        var planReturnTime = row.PLANRETURNTIME;
        var OVERDUESTATUS = nowDateLong-planReturnTime;
        var num=Math.round(OVERDUESTATUS/86400000);
        //两个时间的时间差
        if(num<=-2){
            return '<span  class="label label-success">未逾期</span>';
        }else if(num<=1&num>=-1){
            return '<span class="label label-warning">即将逾期</span>';
        }else if(num>1){
            return '<span class="label label-danger">已逾期</span>';
        }else{
            return ""
        }
    }
    //初始化操作格式
    function actionFormat(value,row,index){
        //续借时间(如果当前有续借时间 则证明当前文件已经发起了续借流程)
        var RENEWRETURNTIME = row.RENEWRETURNTIME;
        var renewTimes = row.RENEWTIMES;
        if(row.BORTYPE==0){
            var arr = [];
            arr.push( '<a class="delete" href="javascript:;" onclick="returnFileAction(' + row.REGISTID + ')" data-toggle="tooltip" title="归还"><i class="glyphicon glyphicon-log-out"></i></a> ');
            if(RENEWRETURNTIME==null&&renewTimes<3){
                arr.push('<a class="delete" href="javascript:;" onclick="renewFileAction(' + index + ')" data-toggle="tooltip" title="续借"><i class="glyphicon glyphicon-repeat"></i></a>');
            }
            return arr.join("");
        }else{
            if(RENEWRETURNTIME==null&&renewTimes<3){
                return [
                    '<a class="update" href="javascript:;" onclick="renewFileAction(' + index +')" data-toggle="tooltip" title="续借"><i class="glyphicon glyphicon-repeat"></i></a>　'
                ].join('');
            }
        }
    }

    //件的操作事项
    function actionFormatter(value,row,index) {
        borType = $("body").attr("attr-id");
        fileShape = $("body").attr("attr-fileShape");
        if(borType==0){
            return [
                '<a class="update" href="javascript:;" onclick="watchOriginal(' + row.itemId +','+fileShape+')" data-toggle="tooltip" title="查看"><i class="glyphicon glyphicon-eye-open"></i></a>　'
            ].join('');
        }else{
            return '--';
        }
    }

    //归还操作
    function returnFileAction(id){
        var rows = $myTable.bootstrapTable('getSelections');
        var ids = [];
        if(id==null||typeof(id)=="undefined"){
            if (rows.length == 0) {
                confirmEvent('请至少选择一条仅且为线上的文件！');
                return;
            }else{
                //默认没有选中线下的内容
                var flag = false;
                for(var index in rows){
                    if(rows[index].BORTYPE==1){
                        flag = true;
                        break;
                    }
                    ids.push(rows[index].REGISTID);
                }
                if(flag){
                    confirmEvent('线下文件不能归还！');
                    return;
                }
            }
        }else{
            ids.push(id);
        }
        Ewin.confirm({ message: "确认归还选中的文件吗？" }).on(function (e) {
            if(!e){
                return;
            }
            $.ajax({
                url:" ${basePath}/pcwindow/returnAccreditArch",
                data:{ids:ids.join("-")},
                type:"post",
                success:function(data){
                    confirmEvent('归还成功！');
                    $myTable.bootstrapTable('refresh');
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    confirmEvent('系统开小差了，请稍后再试!');
                }
            })
        })
    }


    /**************************************** 我的借阅列表数据展示 结束 ***************************************************/

    /**************************************** 续借功能 开始 **************************************************/

    //发起续借操作
    function renewFileAction(index){
        $("#renewButton").attr("disabled",false);
        $("#renewTime").val("");
        $("#renewPurpose").val("");
        //获取当前的续借次数
        var data =  $myTable.bootstrapTable('getData')[index];
        $("#renewTimes").val(data.RENEWTIMES);
        $("#borRegistId").val(data.REGISTID);
        //获取检索申请的流程第一个审批人是否为自定义 若为自定义 则选择已有人员进行设置
        $.ajax({
            url:"${basePath}/activiti/common/selectFirstTaskUser/renewBor/''",
            type:"get",
            async:false,
            dataType:"json",
            success:function(data){
                var code = data.code;
                //当前为指定人选
                if(code==1){
                    $.ajax({
                        url:"${basePath}/pcwindow/showAllUser",
                        type:'get',
                        data:"",
                        dataType:"json",
                        success:function (data) {
                            $('#userTable').empty();
                            $('#userTable').select2({
                                placeholder: '请选择下一个审批人',
                                allowClear: true
                            });
                            var allList = data.rows;
                            var option = '';
                            for(var index in allList){
                                var user = allList[index];
                                option += "<option value='"+user.firstName+"'>"+user.lastName+"</option>";
                            }
                            var $option = $(option);
                            $("#userTable").append($option);
                        }
                    })
                    $("#sendPointUserDiv").show();
                    var pointUser = data.message;
                    $("#userTable").attr("data-delegateUser",pointUser);
                }else{
                    if(data.message!=null){
                        Ewin.alert(data.message);
                    }
                    $("#sendPointUserDiv").hide();
                    $("#userTable").attr("data-delegateUser","");
                }
            }
        })

        $("#renewModal").modal("show");
    }

    //发起续借内容
    function renewSubmit(even){
        $(even).attr("disabled",true);
        var renewTime = $("#renewTime").val();
        var renewTimes = $("#renewTimes").val();
        var renewPurpose = $("#renewPurpose").val();
        var borRegistId = $("#borRegistId").val();
        renewTime = stringToDate(renewTime);
        var flag = validator(renewTime,renewTimes,renewPurpose);
        //替代实际人
        var delegateUser=$("#userTable").attr("data-delegateUser");
        var userName;
        //判断当前是否为指定审批人表达式
        if(delegateUser!=""){
            userName=$("#userTable").val();
            if(userName==null){
                confirmEvent('请指定下一个审批人！');
                $(even).attr("disabled",false);
                return;
            }
        }
        if(flag){
            $.ajax({
                url:"${basePath}/pcwindow/sendRenewAct",
                data:{id:borRegistId,renewPurpose:renewPurpose,renewReturnTime:renewTime,renewTimes:renewTimes,delegateUser:delegateUser,userName:userName},
                type:"post",
                dataType:"json",
                success:function(data){
                    if(data.code==1){
                        confirmEvent('续借申请成功！');
                        $("#renewModal").modal("hide");
                        $myTable.bootstrapTable('refresh');
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    confirmEvent('系统开小差了，请稍后再试!');
                }
            })
        }else{
            $(even).attr("disabled",false);
        }
    }

    //续借内容校验
    function validator(renewTime,renewTimes,renewPurpose){
        var flag = true;
        if(!renewTime){
            confirmEvent('请填写续借时间!');
            flag = false;
            return flag;
        }
        if(renewTimes==3){
            confirmEvent('续借次数最多为3次!');
            flag = false;
            return flag;
        }
        if(renewPurpose==null||""==renewPurpose){
            confirmEvent('续借原因不能为空!');
            flag = false;
            return flag;
        }
        return flag;
    }

    /**************************************** 续借功能 结束 **************************************************/

    //查看原文文件
    function watchOriginal(id,fileShape){
        $("#btn_print").attr("onclick","printAction("+id+","+fileShape+")");
        $("#watchPdfModal").modal("show");
        $("#pdfDIV").attr("src","${basePath}/js/pdfjs/web/viewer.html?data="+new Date().getTime()+"&url_file=${basePath}/pcwindow/watchOriginalImg/"+id+"/"+fileShape);
    }

    //打印iframe中的pdf
    function printAction(id,fileShape) {

        Ewin.confirm({ message: "请确认是否打印？" }).on(function (e) {
            if(!e){
                return;
            }
            $.ajax({
                url:"${basePath}/pcwindow/printRegist",
                type:'post',
                data:{"id":id,"fileShape":fileShape},
                dataType:"json",
                success:function(data){
                    document.getElementById("pdfDIV").contentWindow.print();
                },
                error:function (data) {
                    confirmEvent('系统开小差了，请稍后再试!');
                }
            })
        })
    }

    /**
     * 表格高度自适应
     * @return
     * winTop 浏览器视口高度
     * header 顶部通栏
     * breadcrumb 面包屑
     * mainFooter 底部
     */
    function setHeight(){
        var winTop = $(window.top).height(),
            header = window.top.document.querySelector('.main-header').offsetHeight,
            breadcrumb =  window.top.document.querySelector('.breadcrumb').offsetHeight,
            mainFooter = window.top.document.querySelector('.main-footer').offsetHeight;
        return winTop-header-breadcrumb-mainFooter-10;
    }
</script>
</html>